<template>
	<view class="content">
		<!--搜索框-->
		<view class="content_1">
			<view class="search_box">
				<picker class="search_city" @change="chooseCitys($event,'citys')" :value="data.citys" :range="CitysList"
					range-key="areaName">{{CitysList[data.citys].areaName}}</picker>
				<image class="search_icon" src="../../static/index/down.svg"></image>
				<view class="search_line"></view>
				<input class="search_input" placeholder="搜索理想居住地" placeholder-style="color:#999999;font-size:28upx"
					disabled="true" @click="toSearch"></input>
			</view>
		</view>
		<view style="height: 138upx;"></view>
		<!--筛选-->
		<view class="content_2">
			<view class="screen_view">
				<view class="screen_box" @click="chooseScreen(1)">
					<view :class="[screenstate == '1' ? 'screen_name_active' : 'screen_name']">合/整租</view>
					<image class="screen_icon" src="../../static/index/down_small.svg"></image>
				</view>
				<view class="screen_box" @click="chooseScreen(2)">
					<view :class="[screenstate == '2' ? 'screen_name_active' : 'screen_name']">位置</view>
					<image class="screen_icon" src="../../static/index/down_small.svg"></image>
				</view>
				<view class="screen_box" @click="chooseScreen(3)">
					<view :class="[screenstate == '3' ? 'screen_name_active' : 'screen_name']">租金</view>
					<image class="screen_icon" src="../../static/index/down_small.svg"></image>
				</view>
				<view class="screen_box" @click="chooseScreen(4)">
					<view :class="[screenstate == '4' ? 'screen_name_active' : 'screen_name']">筛选</view>
					<image class="screen_icon" src="../../static/index/down_small.svg"></image>
				</view>
				<view class="screen_box" style="font-size: 28upx; color: #63D0D5; font-weight: bold;"
					@click="chooseScreen(5)">发布</view>
				<!-- <image class="screenIcon" src="../../static/index/screen_icon.svg" v-if="screenIcon" @click="chooseScreen(5)"></image> -->
			</view>
		</view>
		<view style="height: 77upx;"></view>
		<!--房源详细-->
		<view class="content_3">
			<block v-for="(house, index_house) in houseList" :key='index_house'>
				<view class="house_view" @click="toDetail(index_house)">
					<image class="house_img" :src="house.house_image"></image>
					<view class="house_detail">
						<view class="house_name">{{house.house_name}}</view>
						<view class="house_info">
							{{house.house_type}}·{{house.house_direction}}·{{house.house_area}}·{{house.house_floor}}
						</view>
						<view class="house_info">{{house.house_name}}·{{house.house_addr}}</view>
						<view class="house_tips">
							<view class="tips">{{house.house_tips1}}</view>
							<view class="tips">{{house.house_tips2}}</view>
						</view>
						<view class="house_money">¥ {{house.house_money}}/月</view>
					</view>
				</view>
			</block>
		</view>
	</view>
</template>

<script>
	import {Request} from '../../utils/request.js';	//	导入接口请求文件
	import func from '../../utils/function.js'	//	自定义函数文件
	const Func = new func();
	const Requ = new Request();
	const app = getApp();	//定义getApp对象
	// let page = 3
	// let seach_number = 3
	export default {
		data() {
			return {
				data: {
					citys: '0'
				},
				CitysList: [],
				screenstate: '0',		// 切换显示排序列表	1是：合租/整租。 2是：地理位置。 3是：房源租金。 4是：筛选。 5是：发布 6是：选择城市
				page: 0,
				seach_number: 4,
				houseList: [],
				id: '',
				shaixuanstate: false,		// 选择城市筛选状态值 状态为1：表示未筛选，2：表示已做出筛选动作
				cityId: '',
				sortstate: '0',				// 1：升序 2：降序
				openid: '',
				chooserenttypestate: '0',	// 0：整租 1：合租 
				//有我的房屋才显示 这里改为默认显示
				screenIcon: true
			}
		},
		methods: {
			//升序方法
			compare: function(property) {
				return function(a, b) {
					var value1 = a[property];
					var value2 = b[property];
					return value1 - value2;
				}
			},
			//降序方法
			uncompare: function(property) {
				return function(a, b) {
					var value1 = a[property];
					var value2 = b[property];
					return value2 - value1;
				}
			},
			//切换筛选选中状态
			chooseScreen: function(id) {
				this.screenstate = id
				if (id == 1) {
					if (this.chooserenttypestate == '0') {
						let ObjData = 'filter';
						this.houseList = getApp().globalData.houseList
						var arr = this.houseList[ObjData](function(item) {
							return item.renttype == '合租'
						})
						this.houseList = arr
						this.chooserenttypestate = '1';
						this.page = 0;
					} else if (this.chooserenttypestate == '1') {
						this.houseList = getApp().globalData.houseList
						var arr = this.houseList.filter(function(item) {
							return item.renttype == '整租'
						})
						this.houseList = arr
						this.chooserenttypestate = '0'
						this.page = 0;
					}
					// console.log(arr)
				}
				if (id == 2) {
					uni.getLocation({
						success: (res) => {
							console.log(res)
						}
					})
				}
				if (id == 3) {
					this.houseList = getApp().globalData.houseList;
					if (this.sortstate == '0') {
						this.houseList.sort(this.compare('house_money'));
						this.sortstate = '1';
						this.page = 0;
					} else {
						this.houseList.sort(this.uncompare('house_money'));
						this.sortstate = '0';
						this.page = 0;
					}
				}
				if (id == 4) {
					uni.navigateTo({
						url: '/pages/index/push/publish',
					});
					return;
					new Request('customer/push/choose/Upload_Push/write').request(
						() => {
							return 'POST'
						},
						() => {
							return {
								openid: this.openid,
							}
						},
						(res) => {
							if (res.data.code == 1) {
								uni.navigateTo({
									url: '/pages/index/push/publish',
								});
							} else {
								uni.navigateTo({
									url: '/pages/index/push/edit/edit',
									events: {
										// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
										someEvent: (data) => {
											console.log(data)
											//获取房源详细
											new Request('customer/push/choose/Chooes_House/index')
												.request(
													() => {
														return 'POST'
													},
													() => {
														return {
															seach_number: this.seach_number,
															page: this.page,
															openid: app.globalData.openid,
														}
													},
													(res) => {
														console.log(res.data.data)
														if (res.data.code == 0) {
															uni.showToast({
																title: '没有当前地区的房源',
																position: 'center',
																icon: 'none'
															})
															this.houseList = []
														} else {
															this.houseList = res.data.data
															app.globalData.houseList = res.data.data
														}
													}
												);
										}
									},
									success: function(res) {
										// 通过eventChannel向被打开页面传送数据
										res.eventChannel.emit('acceptDataFromOpenerPage', {
											data: 'test'
										})
									}
								});
							}
						}
					);
				}
				if (id == 5) {
					uni.navigateTo({
						url: '/pages/mine/publish',
						// url: '/pages/mine/publish?live_id=' + this.live_id,
					})
				}
			},
			//跳转搜索
			toSearch: function() {
				uni.navigateTo({
					url: '/pages/index/search'
				})
			},
			//	picker选择城市,筛选房源信息
			chooseCitys: function(e, val) {
				let selectValue = e.detail.value;	// picker组件列表下标，默认下标从零排列，零表示用户没有做选择
				let PostData = [];					// 前台路由请求的参数（Object/String/ArrayBuffer）
				this.data[val] = e.target.value
				this.cityId = (this.CitysList[e.target.value].areaId)
				//	当用户不选择城市,获取所有房源信息
				if (selectValue == '0') {
					var PickerUrl = 'Get_House_Info/GetHouseList';		//	服务器接口地址
					PostData['seach_number']	= this.seach_number;	// 查询数目
					PostData['page']			= 0;					// 翻页码
					this.shaixuanstate = '1';	//  变量为1表示 用户没有做任何筛选
					Requ.showToast('请选择城市');
				}
				if(selectValue != '0'){	
					var PickerUrl = 'Search_house/SearchArea';			//	服务器接口地址
					PostData['area_id']			= this.CitysList[e.target.value].areaId;
					PostData['search_area']		= 'city';
					PostData['seach_number']	= this.seach_number;	// 查询数目
					PostData['page']			= 0;					// 翻页码
					this.shaixuanstate = '2';	//  变量为2表示 用户做了除选择第一条之外的筛选
				}
				// 响应
				this.ResponseHouse(PickerUrl, PostData);
				// 记录筛选条件状态值
				this.screenstate = 6;
			},
			/**	响应房源列表数据
			 * @param {Object} url			服务器接口地址
			 * @param {Object} PostData		请求的参数
			 * @param {Object} res			响应回调内容
			 */
			ResponseHouse: function(url, PostData, callBack = false)
			{
				Func.PostApi(url, PostData, (res)=>{
					if(callBack != false){
						callBack(res);
						return;
					}
					if (res.data.code == 0 || res.data.data == -1) {
						Requ.showToast('当前地区的房源为空');
						this.houseList = [];
						return false;
					} else {
						this.houseList = res.data.data;
						app.globalData.houseList = res.data.data;
					}
				});
				return;
			},
			//跳转至详细页,带商品id给后台
			toDetail: function(index) {
				new Request('Get_House_Info/GetHouseDetailInfo').request(
					() => {
						return 'POST'
					},
					() => {
						return {
							house_id: this.houseList[index].id,
							openid: this.openid
						}
					},
					(res) => {
						//判断房源是否售空了
						if (res.data.code != 1) {
							let message = res.data.msg;
							new Request().showToast(message, 'none', () => {
								setTimeout(() => {
									uni.redirectTo({
										url: '/pages/index/index',
									});
								}, 2000);
							});
							return;
						}
						this.id = this.houseList[index].id;
						uni.navigateTo({
							url: '/pages/index/detail/detail?id=' + this.id
						})
					}
				)
			},
			//上拉加载(筛选前)
			loadMore: function() {
				let PostData = [];
				PostData['seach_number']	=	this.seach_number;
				PostData['page']			=	this.page += this.seach_number;
				PostData['DevelopVersion']	=	app.globalData.DevelopVersion;
				PostData['project']			=	app.globalData.project;
				let url = 'Get_House_Info/GetHouseList';			// 获取房源列表地址
				this.ResponseHouse(url, PostData, (res)=>{
					if (res.data.code == 0 || res.data.data == -1) {
						this.page -= this.seach_number;				//	没有更多房源不累加页数
						Requ.showToast('当前地区的房源为空');
						return;
					} else {
						this.houseList = this.houseList.concat(res.data.data)	// 合并房源列表
						// app.globalData.houseList = res.data.data
					}
				});
				return;
			},
			//上拉加载(筛选后)
			loadMore_1: function() {
				console.log('load1')
				new Request('Search_house/SearchArea').request(
					() => {
						return 'POST';
					},
					() => {
						return {
							area_id: this.cityId,
							search_area: 'city',
							seach_number: this.seach_number,
							page: this.page += this.seach_number,
							DevelopVersion: app.globalData.DevelopVersion,
							project: app.globalData.project,
						}
					},
					(res) => {
						//判断有没有房源
						// console.log(res.data.code)
						if (res.data.code == 0 || res.data.data == -1) {
							//没有更多房源不累加页数
							this.page -= this.seach_number;
							new Request().showToast('暂无更多房源信息', 'none', () => {});
						} else {
							this.houseList = this.houseList.concat(res.data.data)
							// app.globalData.houseList = res.data.data
							// console.log(this.houseList)
						}
					}
				);
			},
		},
		onLoad() {
			// 获取城市列表
			Func.PostApi('landboos/Create_House/GetCityList', {city: 1935}, (res) => {
				this.CitysList = res.data.data
				this.CitysList.unshift({
					id: '0',
					areaName: '请选择城市',
				})
			});
			//	获取房源列表
			let PostData = [];
			PostData['seach_number']	= this.seach_number;
			PostData['page']			= this.page;
			// 响应房源列表数据
			this.ResponseHouse('Get_House_Info/GetHouseList', PostData);
		},
		//上拉加载,调用loadMore
		onReachBottom() {
			let str = this.screenstate;		// 切换显示排序列表	1是：合租/整租。 2是：地理位置。 3是：房源租金。 4是：筛选。 5是：发布 6是：选择城市
			let PostData = [];
			let strName = '';
			switch(str){
				case str = 6:
					let that = this;
					if (this.shaixuanstate == '1') {	// 城市picker未做筛选
						setTimeout(function() {
							that.loadMore()
						}, 300);
					}
					if (this.shaixuanstate == '2'){		// 城市picker已做出筛选
						setTimeout(function() {
							that.loadMore_1()
						}, 300);
					}
					break;
				case str = 1:		//	显示（合租/整租）分类
					PostData['seach_number']	= this.seach_number;				// 查询数目
					PostData['page']			= this.page += this.seach_number;	// 翻页码
					strName = this.chooserenttypestate == 1 ? '合租' : '整租';
					this.ResponseHouse('Get_House_Info/GetHouseList', PostData, (res)=>{
						let data = res.data.data;		// 响应内容
						let promise = new Promise((resolve, reject)=>{
							if(Array.isArray(data)){
								resolve(data);
							}else{
								reject();
							}
						});
						promise.then((res)=>{
							let DataArr = res.filter(
								(item) =>{
									return item.renttype == strName;
								}
							);
							this.houseList = this.houseList.concat(DataArr);
						}).catch(()=>{
							this.page -= this.seach_number;
							Requ.showToast('暂无更多房源');
						});
					});
					break;
				case str = 2:		// 地理位置 按远进排序
					
					break;
				case str = 3:		// 房源租金 按高低排序
					PostData['seach_number']	= this.seach_number;				// 查询数目
					PostData['page']			= this.page += this.seach_number;	// 翻页码
					strName = this.sortstate == 1 ? 'compare' : 'uncompare';				// 1：升序 2：降序
					this.ResponseHouse('Get_House_Info/GetHouseList', PostData, (res)=>{
						let data = res.data.data;		// 响应内容
						let promise = new Promise((resolve, reject)=>{
							if(Array.isArray(data)){
								resolve(data);
							}else{
								reject();
							}
						});
						promise.then((res)=>{
							let DataArr = res;
							this.houseList = this.houseList.concat(DataArr);
							this.houseList.sort(this[strName]('house_money'));
						}).catch(()=>{
							this.page -= this.seach_number;
							Requ.showToast('暂无更多房源');
						});
					});
					break;
				default:
					this.loadMore();
			}
			
		},
		//	下拉刷新（重新加载房源列表数据）
		onPullDownRefresh() {
			uni.showToast({
				icon: 'loading',
				position:'center',
				title: '刷新中',
				duration: 1000,
			});
			setTimeout(function() {
				uni.stopPullDownRefresh();
				//	获取房源列表
				let PostData = [];
				PostData['seach_number']	= 10;
				PostData['page']			= this.page;
				// 响应房源列表数据
				this.ResponseHouse('Get_House_Info/GetHouseList', PostData);
			}.bind(this), 1000);
		},
		onShow() {
			//	首页获取openid
			uni.login({
				success: (res) => {
					this.code = res.code;
					let PostData = [];
					let UserLoginUrl 	= 'User_Login/GetUserOpendInfoAndRegister';		// 用户登陆地址
					let UserIsRoomUrl 	= 'customer/push/Is_Customer_House/IsRoom';		// 查询租客是否有已经租房了
					PostData['code']			= this.code;
					PostData['DevelopVersion']	= app.globalData.DevelopVersion;
					PostData['project']			= app.globalData.project;
					let promise = new Promise((resolve, reject)=>{
						Func.PostApi(UserLoginUrl, PostData, (res)=>{
							this.openid = res.data.data.openid;
							this.userid = res.data.data.userid;
							resolve(this.openid);
						});
					});
					promise.then((res)=>{
						Func.PostApi(UserIsRoomUrl, {openid: res,}, (res)=>{
							if (res.data.code == 1) {
								this.screenIcon = true;
								this.live_id = res.data.data.id;
							}
						});
					}).catch(function(res){
						console.log('错误回调' + res);
					});
				}
			});
			
			//	查询用户有没有筛选条件
			if(app.globalData.select_city){
				let PostData = [];
				let AppGlobalData = app.globalData;
				PostData['seach_number'] 		= this.seach_number;
				PostData['page'] 				= this.page;
				//	判断用户 有没有 筛选条件
				Func.is_var(AppGlobalData, 'select_city') == false ? delete PostData['city'] : PostData['city'] = AppGlobalData.select_city;
				Func.is_var(AppGlobalData, 'select_district') == false ? delete PostData['district'] : PostData['district'] = AppGlobalData.select_district;
				Func.is_var(AppGlobalData, 'select_labelName') == false ? delete PostData['label'] : PostData['label'] = AppGlobalData.select_labelName.map(e => {return e.name});
				Func.is_var(AppGlobalData, 'select_chooseTimeId') == false ? delete PostData['chooseTimeId'] : PostData['chooseTimeId'] = AppGlobalData.select_chooseTimeId;
				Func.is_var(AppGlobalData, 'select_startmoney') == false ? delete PostData['startmoney'] : PostData['startmoney'] = AppGlobalData.select_startmoney;
				Func.is_var(AppGlobalData, 'select_endmoney') == false ? delete PostData['endmoney'] : PostData['endmoney'] = AppGlobalData.select_endmoney;
				Func.is_var(AppGlobalData, 'select_livingId') == false ? delete PostData['livingId'] : PostData['livingId'] = AppGlobalData.select_livingId;
				Func.is_var(AppGlobalData, 'select_bedId') == false ? delete PostData['bedId'] : PostData['bedId'] = AppGlobalData.select_bedId;
				Func.is_var(AppGlobalData, 'select_toiletId') == false ? delete PostData['toiletId'] : PostData['toiletId'] = AppGlobalData.select_toiletId;
				Func.is_var(AppGlobalData, 'select_hotid') == false ? delete PostData['hotId'] : PostData['hotId'] = AppGlobalData.select_hotid;
				
				
				let url = 'Get_House_Info/select_house';	// 筛选房源条件列表
				// 响应房源列表数据
				this.ResponseHouse(url, PostData);
				return;
			}else{
				this.houseList = app.globalData.houseList;
			}
		}
	}
</script>

<style>
	page {
		background-color: #F9F9F9;
	}

	/*
		搜索框样式
	*/
	.content_1 {
		height: 90upx;
		width: 678upx;
		padding: 24upx 38upx;
		background-color: #FFFFFF;
		position: fixed;
		z-index: 999;
		top: 0upx;
		left: 0upx;
	}

	.search_box {
		height: 35upx;
		border-radius: 18upx;
		background-color: #F1F3F4;
		padding: 25upx 30upx 30upx 30upx;
		display: flex;
		align-items: center;
	}

	.search_city {
		height: 37upx;
		font-size: 28upx;
		line-height: 37upx;
		color: #666666;
		margin-right: 13upx;
	}

	.search_icon {
		width: 50upx;
		height: 50upx;
		margin-right: 27upx;
	}

	.search_line {
		width: 3upx;
		height: 33upx;
		background-color: #979797;
		margin-right: 34upx;
	}

	.search_input {
		height: 37upx;
		line-height: 37upx;
		font-size: 28upx;
	}

	/*
		筛选样式
	*/
	.content_2 {
		height: 37upx;
		width: 678upx;
		background-color: #FFFFFF;
		padding: 13upx 38upx 27upx 38upx;
		position: fixed;
		z-index: 999;
		top: 136upx;
		left: 0upx;
	}

	.screen_view {
		height: 37upx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.screen_box {
		height: 37upx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.screen_name {
		height: 37upx;
		line-height: 37upx;
		font-size: 28upx;
		color: #999999;
		margin-right: 8upx;
	}

	.screen_name_active {
		height: 37upx;
		line-height: 37upx;
		font-size: 28upx;
		color: #B3E9DC;
		margin-right: 8upx;
	}

	.screen_icon {
		width: 28upx;
		height: 28upx;
	}

	.screenIcon {
		height: 38upx;
		width: 38upx;
		transform: rotate(90deg);
		background-color: #007AFF;
	}

	/*
		房源详细样式
	*/
	.content_3 {
		margin-top: 40upx;
		padding-bottom: 150upx;
	}

	.house_view {
		height: 246upx;
		background-color: #FFFFFF;
		border-radius: 15upx;
		padding: 27upx 24upx;
		margin-bottom: 40upx;
		display: flex;
		align-items: center;
	}

	.house_img {
		width: 304upx;
		height: 246upx;
		background-color: #8E83C7;
		margin-right: 24upx;
	}

	.house_detail {
		height: 258upx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.house_name {
		height: 43upx;
		line-height: 43upx;
		font-size: 32upx;
		color: #333333;
	}

	.house_info {
		width: 400upx;
		height: 35upx;
		line-height: 35upx;
		font-size: 26upx;
		color: #999999;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.house_tips {
		height: 30upx;
		display: flex;
	}

	.tips {
		height: 30upx;
		line-height: 30upx;
		color: #FFFFFF;
		font-size: 20upx;
		background-image: linear-gradient(to right, #87ECC6, #8ED5EE); //颜色渐变效果(从左到右)
		margin-right: 16upx;
		padding: 0upx 20upx;
	}

	.house_money {
		height: 46upx;
		line-height: 46upx;
		font-size: 34upx;
		color: #FFC26D;
	}
</style>
